package com.antler.smt.portal.service.impl;

import com.antler.smt.constant.IdentifiyingCodeConstant;
import com.antler.smt.entity.MemberEntity;
import com.antler.smt.enums.ResultCodeEnum;
import com.antler.smt.portal.mapper.MemberEntityMapper;
import com.antler.smt.portal.utils.MailUtil;
import com.antler.smt.portal.utils.RedisUtil;
import com.antler.smt.request.portal.SendReq;
import com.antler.smt.response.base.Result;
import com.antler.smt.service.portal.IdentifyingCodeService;
import com.antler.smt.utils.LogUtil;
import com.antler.smt.utils.RandomCodeUtil;
import com.antler.smt.utils.SmsUtil;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 验证码发送验证接口实现
 *
 * @author zhangyi
 * @date 2018/4/2 10:44
 */
@Service
public class IdentifyingCodeServiceImpl implements IdentifyingCodeService {

    /**
     * 日志
     */
    public static Logger log = LogUtil.get();


    @Autowired
    private MemberEntityMapper memberEntityMapper;

    /**
     * 缓存工具类
     */
    @Autowired
    private RedisUtil redisUtil ;

    /**
     * 邮件工具类
     */
    @Autowired
    private MailUtil mailUtil;

    /**
     * 发送验证码
     *
     * @param id 当前用户id
     * @param receiver 邮件接收者
     * @return
     */
    @Override
    public Result sendCode(String id,SendReq receiver) {
        Result result = null;

        //生成6位随机码
        String randomNumCode = RandomCodeUtil.getRandomNumCode(6);

        //存入缓存 有效期5分钟
        redisUtil.set(id,randomNumCode, IdentifiyingCodeConstant.SECOND);

        MemberEntity memberEntity =
                memberEntityMapper.selectByPrimaryKey(Long.parseLong(id));

        if(!("null".equalsIgnoreCase(memberEntity.getEmail())) && !("".equalsIgnoreCase(memberEntity.getEmail()))){
            //发送邮件
            mailUtil.sendSimpleMail(receiver.getEmail(),
                    IdentifiyingCodeConstant.CODE_THEME,
                    IdentifiyingCodeConstant.CODE_CONTENT+randomNumCode);
            result = new Result(ResultCodeEnum.OPERATION_SUCCESS,"邮件发送成功");
        }else if(!("null".equalsIgnoreCase(memberEntity.getMobile())) && !("".equalsIgnoreCase(memberEntity.getMobile()))){
            //发送短信
            SmsUtil.sendCodeSms(receiver.getMobile(),randomNumCode);
            result = new Result(ResultCodeEnum.OPERATION_SUCCESS,"短信发送成功");
        }else{
            result = new Result(ResultCodeEnum.MODIFY_DATA_ERROR,"发送信息失败！");
        }
        return result;
    }
}
